#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>

#include <functional>

#include "Log.hpp"
#include "InerAddr.hpp"

using namespace std;

const static int defaultsockfd = -1;
const static int backlog = 16;
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR,
    LISTEN_ERROR,
};
class TcpServer;

class ThreadData
{
public:
    ThreadData(int fd, InetAddr client, TcpServer *s) : sockfd(fd), clientaddr(client), self(s)
    {
    }
    ~ThreadData()
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

using func_t =std::function<string(const string&)>;

class TcpServer
{
public:
    TcpServer(int port,func_t func) : _port(port), _listensockfd(defaultsockfd), _isrunning(false),_func(func)
    {
    }
    void InitServer()
    {
        // 1.创建流式套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _listensockfd);

        // 2.bind
        //  2.0 填充sockaddr_in结构
        struct sockaddr_in local; // struct sockaddr_in 系统提供的数据类型。local是变量，用户栈上开辟空间。int a = 100; a = 20;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // htonl(INADDR_ANY);

        // 2.1 bind sockfd和网络信息(IP(?) + Port)
        int n = bind(_listensockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");

        // 3.tcp是面向链接的，通信之前必须建立连接;服务器是被连接的
        //  tcpserver启动了，要先等待客户的连接到来
        n = listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(FATAL, "listen error, %s, %d\n", strerror(errno), errno);
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "socket listen success\n");
    }

    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link info %s:%d\n", client.Ip().c_str(), client.Port());
        string clientaddr = "[" + client.Ip() + ":" + to_string(client.Port()) + "]# ";
        while (true)
        {
            char buffer[1024];
            //tcp是面向字节流的，不能保证buffer，是一个完整的指令 ，例如“ls -a -l"
            //他有可能第一次只读到了l，第二次督导了s -a -l
            ssize_t n = recv(sockfd, &buffer, sizeof(buffer) - 1,0);//bug
            if (n > 0)
            {
                buffer[n] = 0;
                cout << clientaddr << buffer << endl;

                string result=_func(buffer);

                send(sockfd, result.c_str(), result.size(),0);
            }
            else if (n == 0) // 退出&&关闭连接
            {
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }
        }
        close(sockfd); // 不关闭就会有文件描述泄漏
    }
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->Service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        // 4.不能直接接受数据，要先获取连接
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            pthread_t t;
            ThreadData* td=new ThreadData(sockfd,InetAddr(peer),this);
            pthread_create(&t,nullptr,HandlerSock,td);//将线程设置为分离状态


        }
    }
    ~TcpServer()
    {
        if (_listensockfd > defaultsockfd)
            close(_listensockfd);
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;

    func_t _func;
};